package us.lithub.ui.dialog;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import us.lithub.R;
import us.lithub.data.Book;
import us.lithub.data.ItemLookup;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.fedorvlasov.lazylist.ImageLoader;

/**
 * The Class DetailedBookInfo class shows more information about a book
 */
public class DetailedBookInfo extends Activity implements OnClickListener, RatingBar.OnRatingBarChangeListener{

	private static final String TAG = DetailedBookInfo.class.getSimpleName();
	private Book currBook;
	private RatingBar rbar;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_detailed_book_info);
	
		//get row id, query relevant info to display
		Bundle tempB = getIntent().getExtras();
		String bookisbn = (String) tempB.getString("BookISBN");
		currBook = ItemLookup.findProduct(bookisbn);
		((TextView) findViewById(R.id.book_title)).setText("Title: \t"+currBook.getTitle());
		((TextView) findViewById(R.id.book_author)).setText("Author: \t"+currBook.getAuthor());
		((TextView) findViewById(R.id.book_publisher)).setText("Publisher: \t"+currBook.getPublisher());
		((TextView) findViewById(R.id.book_ISBN)).setText("ISBN: \t"+bookisbn);
		((TextView) findViewById(R.id.book_description)).setText(currBook.getSummary());
		rbar = (RatingBar) findViewById(R.id.ratingBar1);
		rbar.setRating( (float) currBook.getMyRating());
		rbar.setOnRatingBarChangeListener(this);
		// Lazy load the cover image
		ImageView image = (ImageView)findViewById(R.id.imview);
		String tempurl ="http://covers.openlibrary.org/b/isbn/"+bookisbn+"-M.jpg";

		try{
			URL url = new URL(tempurl);
			HttpURLConnection c = (HttpURLConnection) url.openConnection();
			HashMap<String, List<String>> m= new HashMap<String, List<String>>();
			m= (HashMap<String, List<String>>) c.getHeaderFields();
			if (! m.containsKey("Content-Type") || !m.containsKey("content-type") )//check if content is empty, then show generic book
				image.setImageResource(R.drawable.generic_book);
			else
				new ImageLoader(this).DisplayImage(tempurl, image);
		} catch (MalformedURLException mal){
			Log.e(TAG, mal.getMessage());
		} catch (IOException io){
			Log.e(TAG, io.getMessage());
		} 
	}

	@Override
	public void onClick(View v) {
		finish();
	}

	@Override
	public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
		currBook.setMyRating((float)rating);	//need to go into user db
		
		ratingBar.setRating(rating);
		Toast.makeText(DetailedBookInfo.this, "New Rating: " + rating, Toast.LENGTH_SHORT).show();

	}
}